<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
	<title>范闲商城-提交订单</title>
	<link rel="stylesheet" type="text/css" th:href="@{/static/css/reset.css}">
	<link rel="stylesheet" type="text/css" th:href="@{/static/css/main.css}">
	<link rel="stylesheet" th:href="@{/static/layui/css/layui.css}">
	<script th:src="@{/static/jquery-2.1.4.js}" type="text/javascript" charset="utf-8"></script>
	<script th:src="@{/static/layui/layui.js}" type="text/javascript" charset="utf-8"></script>
	<script th:src="@{/static/mylayer.js}" type="text/javascript" charset="utf-8"></script>
	<style>
		.layui-table th, .layui-table td {
			text-align: center;
		}
		.avatar-img {
			width: 20px; /* 设置头像图片的宽度 */
			height: 20px; /* 设置头像图片的高度，可以根据需要调整 */
			border-radius: 50%; /* 使图片呈现圆形 */
			margin-right: 10px; /* 设置头像图片与用户名之间的间距，可以根据需要调整 */
		}
		.order_submit a {
			margin-left: 20px; /* 增加右侧间距 */
		}
		.letter-box{
			width: 100%;
			height: 176px;
			padding: 3px;
			box-sizing: border-box;
		}
		.letter-border{
			width: 100%;
			height: 100%;
			background: #FFFFFF;
		}

		.letter-box {
			width: 24%;
			height: 150px;
			padding: 5px;
			box-sizing: border-box;
			background: linear-gradient(45deg,#f25953 12.5%,#fbfaf5 12.5%,#fbfaf5 25%,#5590d6 25%,#5590d6 37.5%,#fbfaf5 37.5%,#fbfaf5 50%,#f25953 50%,#f25953 62.5%,#fbfaf5 62.5%,#fbfaf5 75%,#5590d6 75%,#5590d6 87.5%,#fbfaf5 87.5%,#fbfaf5 100%);
			background-size: 70px 70px;
		}

		.letter-box.unselected {
			/*未选中状态的边框颜色 */
			background: linear-gradient(45deg,#E8E8E8 12.5%,#fbfaf5 12.5%,#fbfaf5 25%,#E8E8E8 25%,#E8E8E8 37.5%,#fbfaf5 37.5%,#fbfaf5 50%,#E8E8E8 50%,#E8E8E8 62.5%,#fbfaf5 62.5%,#fbfaf5 75%,#E8E8E8 75%,#E8E8E8 87.5%,#fbfaf5 87.5%,#fbfaf5 100%);
			background-size: 70px 70px;
			
		}
		.letter-box.unselected .actions {
			display: none;
		}

		.letter-box .actions {
			display: block;
		}
		.letter-box {
			width: 24%; /* 调整宽度为24%，以适应一行四个 */
			margin: 0.5%; /* 调整外边距以增加间隙 */
		}

		.letter-box-container {
			display: flex; /* 使用 Flexbox 布局 */
			justify-content: flex-start; /* 在项目之间平均分配空间 */
			flex-wrap: wrap; /* 允许项目换行 */
			margin: 20px 0; /* 添加一些外边距 */
		}
		.consignee {
			padding:10px  14px  10px  14px;
		}
		.letter-border {
			display: flex; /* 使用 Flexbox 布局 */
			flex-direction: column; /* 子元素垂直排列 */
			justify-content: space-between; /* 分散对齐，推动最后一个子元素到底部 */
			height: 100%; /* 确保占满整个父容器的高度 */
		}
		.letter-border > div:last-child {
			text-align: right;
			padding-right: 14px; /* 右侧距离 */
			margin-bottom: 10px; /* 底部距离 */
		}

		.coupon_select {
			margin-top: 10px;
			margin-left: 20px;
		}
		.coupon_select label {
			margin-right: 5px;
		}
		.coupon_select select {
			padding: 5px;
		}
		.coupon_select button {
			padding: 5px 10px;
			background-color: #337ab7;
			color: #fff;
			border: none;
			cursor: pointer;
		}
	</style>


</head>
<body>
	<div th:replace="header::top"></div>

	<div class="search_bar clearfix">
		<a href="/" class="logo fl"><img src="/static/pic/fanxian-mall.png" width="150px" height="60px"></a>
		<div class="sub_page_name fl">|&nbsp;&nbsp;&nbsp;&nbsp;提交订单</div>
		<div class="search_con fr">
			<input type="text" id="searchInput" class="input_text fl" placeholder="搜索商品">
			<input type="button" id="searchButton" class="input_btn fr" value="搜索">
		</div>		
	</div>
	
	<h3 class="common_title">确认收货地址</h3>

	<div class="common_list_con clearfix">
		<dl>
			<a href="/page/user/site.html"><button type="button" class="layui-btn layui-bg-blue">管理收货地址</button></a>
			<button type="button" class="layui-btn layui-bg-blue" id="addShipping">新建收货地址</button>

			<div class="letter-box-container" id="ShippingList">

			</div>

		</dl>



	</div>

	<h3 class="common_title">支付方式</h3>	
	<div class="common_list_con clearfix">
		<div class="pay_style_con clearfix">
			<input type="radio" name="paymentType" value="0">
			<label class="cash">货到付款</label>
			<input type="radio" name="paymentType" value="1">
			<label class="weixin">微信支付</label>
			<input type="radio" name="paymentType" value="2" checked="">
			<label class="zhifubao"></label>
			<input type="radio" name="paymentType" value="3">
			<label class="bank">银行卡支付</label>
		</div>
	</div>

	<h3 class="common_title">商品列表</h3>
	
	<div class="common_list_con clearfix">
		<table class="layui-table" lay-skin="line">
			<colgroup>
				<col width="5%">
				<col width="25%">
				<col width="25%">
				<col width="15%">
				<col width="15%">
				<col width="15%">
				<col>
			</colgroup>
			<thead>
			<tr>
				<th></th>
				<th>商品图片</th>
				<th>商品名称</th>
				<th>商品价格</th>
				<th>数量</th>
				<th>小计</th>
			</tr>
			</thead>
			<tbody id="LAY_OrderCartList">
			<tr>
				<th>1</th>
				<th><img src="/static/images/goods/goods003.jpg"></th>
				<th>大兴大棚草莓</th>
				<th>16.80元</th>
				<th>1</th>
				<th>16.80元</th>
			</tr>
			</tbody>
		</table>
	</div>

	<h3 class="common_title">总金额结算</h3>

	<div class="common_list_con clearfix">
		<div class="coupon_select">
			<label for="coupon">优惠券：</label>
			<select name="coupon" id="coupon">
				<option value="">请选择优惠券</option>
			</select>
			<button type="button" id="couponButton">使用优惠券</button>
		</div>
		<div class="settle_con">
			<div class="total_goods_count">共<em>2</em>件商品<br>总金额<b>42.60元</b></div>
			<div class="transit">运费：<b>10元</b></div>
			<div class="transit">优惠券抵扣：<b id="discount">0元</b></div>
			<div class="total_pay">实付款：<b>52.60元</b></div>
		</div>
		<dl style="text-align: right;">
			<div id="shippingConfirm">
			</div>
		</dl>
	</div>

	<div class="order_submit clearfix">
		<a href="javascript:;" id="order_btn">提交订单</a>
		<a href="javascript:;" id="continue_btn">继续选择</a>
	</div>


	<div class="footer">
		<div class="foot_link">
			<a href="#">关于我们</a>
			<span>|</span>
			<a href="#">联系我们</a>
			<span>|</span>
			<a href="#">招聘人才</a>
			<span>|</span>
			<a href="#">友情链接</a>		
		</div>
		<p>CopyRight © 2024 北京鑫鑫科技有限公司 All Rights Reserved</p>
		<p>电话：010-8888888    京ICP备88888888号</p>
	</div>

	<script type="text/javascript" src="js/jquery-1.12.2.js"></script>
	<script type="text/javascript">
		$('#continue_btn').click(function () {
			history.back();
		})
		$('#searchButton').click(function() {
			var searchText = $('#searchInput').val(); // 获取搜索框中的值
			var searchUrl = '/page/list?search=' + encodeURIComponent(searchText); // 构建带有搜索关键字的URL
			window.location.href = searchUrl; // 跳转到另一个页面
		});
		var queryString = window.location.search;
		var urlParams = new URLSearchParams(queryString);
		var productId = urlParams.get("productId");
		var quantity = urlParams.get("quantity");
		$('#addShipping').click(function () {
			layer.open({
				type: 2,
				title: '新建收货地址',
				area: ['50%', '75%'],// 宽高
				content: '/page/shipping/add',
			});
		});
		$.post(
				'/shipping/ListByUerId',
				function (result) {
					if (result.code == 0) {
						var html = '';
						$('#ShippingList').empty();
						$(result.data).each(function () {
							if (this.checked == 1) {
								html += '<div class="letter-box" id="'+this.id+'" >'
								html += '	<input type="hidden" id="'+this.checked+'">'
								html += '	<div class="letter-border">'
								html += '		<div class="consignee">'
								html += '			<div style="display: flex; justify-content: space-between;">'
								html += '				<div>收货人：<em>'+this.receiverName+'</em></div>'
								html += '				<div style="text-align: right; background-color: #E0E0E0; color: white;">默认地址</div>'
								html += '			</div>'
								html += '			<div>手机号：'+this.receiverMobile+'</div>'
								html += '			<div>收货地址：'+this.receiverProvince+''
								if (this.receiverCity === '市辖区'|| this.receiverCity === '县') {
									html += ' '
								} else {
									html += '					'+this.receiverCity+''
								}
								html += '					'+this.receiverArea+' '+this.receiverAddress+'</div>'
								html += '		</div>'
								html += '		<div style="text-align: right;" class="actions">'
								html += '			<a href="javascript:;" style="color: #FF9900;" id="updateShipping">修改</a>'
								html += '			<a href="javascript:;" style="margin-left: 10px; color: #FF9900;" id="deleteShipping">删除</a>'
								html += '		</div>'
								html += '	</div>'
								html += '</div>'
							} else {
								html += '<div class="letter-box" id="'+this.id+'" >'
								html += '	<input type="hidden" id="'+this.checked+'">'
								html += '	<div class="letter-border">'
								html += '		<div class="consignee">'
								html += '			<div style="display: flex; justify-content: space-between;">'
								html += '				<div>收货人：<em>'+this.receiverName+'</em></div>'
								html += '				<div style="text-align: right; background-color: #E0E0E0;" class="actions"><a href="javascript:;" style=" color: white;" id="default">设为默认</a></div>'
								html += '			</div>'
								html += '			<div>手机号：'+this.receiverMobile+'</div>'
								html += '			<div>收货地址：'+this.receiverProvince+''
								if (this.receiverCity === '市辖区'|| this.receiverCity === '县') {
									html += ' '
								} else {
									html += '					'+this.receiverCity+''
								}
								html += '					'+this.receiverArea+' '+this.receiverAddress+'</div>'
								html += '		</div>'
								html += '		<div style="text-align: right;" class="actions">'
								html += '    		<a href="javascript:;" style="color: #FF9900;" id="updateShipping">修改</a>'
								html += '    		<a href="javascript:;" style="margin-left: 10px; color: #FF9900;" id="deleteShipping">删除</a>'
								html += '		</div>'
								html += '	</div>'
								html += '</div>'
							}
						});
						$('#ShippingList').append(html);
						$(function() {
							$('.letter-box').each(function() {
								var id = $(this).find('input').attr('id');
								if (id === '1') {
									$(this).removeClass('unselected');
									$(this).attr('checked','checked');
								} else {
									$(this).addClass('unselected');
									$(this).removeAttr('checked');
								}
							});

							//$('.letter-box').click(function() {
							$('#ShippingList').on('click', '.letter-box',function() {
								$('.letter-box').addClass('unselected');
								$('.letter-box').removeAttr('checked');
								$(this).removeClass('unselected');
								$(this).attr('checked','checked');
							});

						});
						$('#ShippingList').on('click', '#deleteShipping',function() {
						//$('#deleteShipping').click(function() {

							var id = $(".letter-box[checked='checked']").attr('id')
							layer.confirm(
									'您确定要删除吗？',
									{icon : 3},
									function (index) {
										$.post(
												'/shipping/delete',
												{'id': id,},
												function (result) {
													if (result.code == 0) {
														mylayer.okMsg(result.msg);
														window.location.reload();
													}
												},
												'json'
										);
									}
							)

						});
						$('#ShippingList').on('click', '#default',function() {

							var id = $(".letter-box[checked='checked']").attr('id')
							layer.confirm(
									'您确定要设置为默认地址吗？',
									{icon : 3},
									function (index) {
										$.post(
												'/shipping/updateDefault',
												{'id': id,},
												function (result) {
													if (result.code == 0) {
														mylayer.okMsg(result.msg);
														window.location.reload();
													}
												},
												'json'
										);
									}
							)

						});
						$('#ShippingList').on('click', '#updateShipping',function() {

							var id = $(".letter-box[checked='checked']").attr('id')

							layer.open({
								type: 2,
								title: '修改收货地址',
								area: ['50%', '75%'],// 宽高
								content: '/page/shipping/update?id='+id,
							});

						});
						$.post(
								'/shipping/shippingById',
								{'shippingId': $(".letter-box[checked='checked']").attr('id')},
								function (result) {
									if (result.code == 0) {
										var html = '';
										$('#shippingConfirm').empty();
										$(result.data).each(function () {
											html += '<div>'
											html += '	<em class="layui-inline" style="font-weight:bold;">寄送到：</em>'
											html += '	<em class="layui-inline">' + this.receiverProvince + '</em>'
											if (this.receiverCity === '市辖区' || this.receiverCity === '县') {
												html += ' '
											} else {
												html += '<em class="layui-inline">' + this.receiverCity + '</em>'
											}
											html += '	<em class="layui-inline">' + this.receiverArea + '</em>'
											html += '	<em class="layui-inline">' + this.receiverAddress + '</em>'
											html += '</div>'
											html += '<div>'
											html += '	<em class="layui-inline" style="font-weight:bold;">收货人：</em>'
											html += '	<em class="layui-inline">' + this.receiverName + '</em>'
											html += '	<em class="layui-inline">' + this.receiverMobile + '</em>'
											html += '</div>'
										});
										$('#shippingConfirm').append(html);
									}
								},
								'json'
						);
						$('#ShippingList').on('click', '.letter-box',function() {
							$.post(
									'/shipping/shippingById',
									{'shippingId': $(".letter-box[checked='checked']").attr('id')},
									function (result) {
										if (result.code == 0) {
											var html = '';
											$('#shippingConfirm').empty();
											$(result.data).each(function () {
												html += '<div>'
												html += '	<em class="layui-inline" style="font-weight:bold;">寄送到：</em>'
												html += '	<em class="layui-inline">' + this.receiverProvince + '</em>'
												if (this.receiverCity === '市辖区' || this.receiverCity === '县') {
													html += ' '
												} else {
													html += '<em class="layui-inline">' + this.receiverCity + '</em>'
												}
												html += '	<em class="layui-inline">' + this.receiverArea + '</em>'
												html += '	<em class="layui-inline">' + this.receiverAddress + '</em>'
												html += '</div>'
												html += '<div>'
												html += '	<em class="layui-inline" style="font-weight:bold;">收货人：</em>'
												html += '	<em class="layui-inline">' + this.receiverName + '</em>'
												html += '	<em class="layui-inline">' + this.receiverMobile + '</em>'
												html += '</div>'
											});
											$('#shippingConfirm').append(html);
										}
									},
									'json'
							);
						})
					}
				},
				'json'
		);

		var order = {
			couponId: null,
			postage: 10,
			discount: 0,
		};

		$.post(
				'/coupon/selectByUserIdNowBuy',
				{'productId': productId, 'quantity': quantity},
				function (result) {
					console.log(result);
					if (result.code == 0) {
						$(result.data).each(function () {
							$('#coupon').append('<option value="'+this.id+'">'+this.couponName+'</option>');
						})
						//form.render('select');
					}
				},
				'json'
		);

		$('#couponButton').click(function() {
			// 获取选择框中所选项的值
			var selectedCouponId = $('#coupon').val();

			// 在控制台输出所选优惠券的id
			console.log('Selected Coupon ID: ' + selectedCouponId);

			// 在这里可以进行其他操作，比如根据所选优惠券id执行相应的逻辑

			if (selectedCouponId == null || selectedCouponId == '') {
				$("#discount").text("0元");
				var totalPrice = parseFloat($('.total_goods_count b').text());
				var shippingCost = parseFloat($('.transit').eq(0).find('b').text());

				// 计算实付款
				var finalPayment = totalPrice + shippingCost;
				$('.total_pay b').text(finalPayment.toFixed(2) + '元'); // 更新实付款金额，保留两位小数
				order.discount = 0;
				order.couponId = null;
				console.log(order);
			} else {
				$.post(
						'/coupon/selectById',
						{'id': selectedCouponId},
						function (result) {
							console.log(result);
							if (result.code == 0) {
								$("#discount").text(result.data.discount+"元");
								var totalPrice = parseFloat($('.total_goods_count b').text());
								var shippingCost = parseFloat($('.transit').eq(0).find('b').text());
								var discount = parseFloat(result.data.discount);
								var finalPayment = totalPrice + shippingCost + discount;
								$('.total_pay b').text(finalPayment.toFixed(2) + '元');
								order.discount = discount;
								order.couponId = selectedCouponId;
								console.log(order);
							}
						},
						'json'
				);
			}


		});

		$.post(
				'/product/selectByProductId',
				{'id': productId},
				function (result) {
					if (result.code == 0) {
						var html = '';
						var count = 1; // 初始化计数器
						var totalQuantity = quantity; // 初始化商品总数量
						var totalPrice = 0; // 初始化总金额
						$('#LAY_OrderCartList').empty();
						$(result.data).each(function () {
							html += '<tr>'
							html += '	<th>'+count+'</th>'
							html += '	<th><img src="'+this.mainImage+'"></th>'
							html += '	<th>'+this.name+'</th>'
							html += '	<th>'+this.price+'元</th>'
							html += '	<th>'+quantity+'</th>'
							html += '	<th>'+(quantity*this.price)+'元</th>'
							html += '</tr>'
							count++;
							totalPrice = quantity * this.price; // 累加总金额
						});
						$('#LAY_OrderCartList').append(html);
						$('.total_goods_count em').text(totalQuantity); // 更新商品总数量
						$('.total_goods_count b').text(totalPrice.toFixed(2) + '元'); // 更新总金额，保留两位小数
						// 读取运费和优惠券折扣
						var shippingCost = parseFloat($('.transit').eq(0).find('b').text());
						var discount = parseFloat($('.transit').eq(1).find('b').text());

						// 计算实付款
						var finalPayment = totalPrice + shippingCost + discount; // 注意优惠券折扣通常为负数
						$('.total_pay b').text(finalPayment.toFixed(2) + '元'); // 更新实付款金额，保留两位小数
					}
				},
				'json'
		);


		console.log(order);

		$('#order_btn').click(function () {
			$.post(
					'/order/buyNow',
					{'shippingId': $(".letter-box[checked='checked']").attr('id'), 'paymentType': $("input[name='paymentType']:checked").val(), 'couponId': order.couponId, 'postage': 10,'discount': order.discount, 'productId': productId, 'quantity': quantity},
					function (result) {
						console.log(result);
						if (result.code == 0) {
							mylayer.okUrl(result.msg, '/page/user/order');
						} else {
							mylayer.errorMsg(result.msg);
						}
					},
					'json'
			);
		});


		function logout() {
			layer.confirm(
					'您确认要退出么',
					{icon:3},
					function() {
						$.post(
								'/user/logout',
								function (result) {
									if (result.code == 0) {
										mylayer.okMsg(result.msg);
										setTimeout(function() {
											window.location.reload();
										}, 800);
									}
								},
								'json'
						);
						// location.href = '/admin?method=logout'
					}
			);
		}

	</script>
</body>
</html>